package com.sample;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.ivsign.lib_idcardidentification.IDCardIdentificationManager;

import java.util.ArrayList;
import java.util.List;

public class ConnectSampleActivity extends Activity {


    private static final String TAG = "BluetoothTest";

    private Button btnSearch, btnDis, btnExit;
    private ToggleButton tbtnSwitch;

    private ListView lvBTDevices;
    private ArrayAdapter<String> adtDevices;
    private List<String> lstDevices = new ArrayList<String>();

    private List<String> mac = new ArrayList<>();

    @Override
    protected void onResume() {
        super.onResume();
    }


    ProgressDialog pd;
    Activity ac;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        List<BLEDeviceInfo.BleBean> ble = BLEApplication.getBle();
        for (BLEDeviceInfo.BleBean bleBean : ble) {
            mac.add(bleBean.getMac());
        }


        // Button 设置
        btnSearch = (Button) this.findViewById(R.id.btnSearch);
        btnSearch.setOnClickListener(new ConnectSampleActivity.ClickEvent());

        btnExit = (Button) this.findViewById(R.id.btnExit);
        btnExit.setOnClickListener(new ConnectSampleActivity.ClickEvent());

        btnDis = (Button) this.findViewById(R.id.btnDis);
        btnDis.setOnClickListener(new ConnectSampleActivity.ClickEvent());

        // ToogleButton设置
        tbtnSwitch = (ToggleButton) this.findViewById(R.id.tbtnSwitch);
        tbtnSwitch.setOnClickListener(new ConnectSampleActivity.ClickEvent());

        // ListView及其数据源 适配器
        lvBTDevices = (ListView) this.findViewById(R.id.lvDevices);
        adtDevices = new ArrayAdapter<String>(ConnectSampleActivity.this,
                android.R.layout.simple_list_item_1, lstDevices);
        lvBTDevices.setAdapter(adtDevices);
        lvBTDevices.setOnItemClickListener(new ConnectSampleActivity.ItemClickEvent());

        //jiemi();
        ac = this;

    }


    @Override
    protected void onDestroy() {

        super.onDestroy();

    }

    static BluetoothDevice btDev;


    @SuppressLint("NewApi")
    class ItemClickEvent implements AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                long arg3) {

            String str = lstDevices.get(arg2);
            String[] values = str.split("\\|");
            final String address = values[1];
            Log.e("address", values[1]);
            pd = new ProgressDialog(ac);
            pd.setProgressStyle(TRIM_MEMORY_RUNNING_CRITICAL);
            pd.setMessage("正在配对。。");
            pd.setTitle("配对address");
            pd.show();


            IDCardIdentificationManager.getInstance().connect(address, new BleGattCallback() {
                @Override
                public void onStartConnect() {

                }

                @Override
                public void onConnectFail(BleDevice bleDevice, BleException exception) {
                    // 连接失败
                    Toast.makeText(ConnectSampleActivity.this, "连接失败" + exception.getDescription(), Toast.LENGTH_SHORT).show();
                    pd.dismiss();
                }

                @Override
                public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
                    Toast.makeText(ConnectSampleActivity.this, "连接成功,进入读证界面", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent();
                    intent.putExtra(Constant.mac, address);
                    intent.putExtra(Constant.serviceData, bleDevice);
                    intent.setClass(ConnectSampleActivity.this, ReadIDSampleActivity.class);
                    startActivity(intent);
                    pd.dismiss();
                }

                @Override
                public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {

                }
            });


        }
    }

    @Override
    protected void onPause() {
        super.onPause();

    }

    private class ClickEvent implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if (v == btnSearch)// 搜
            // 索蓝牙设备，在BroadcastReceiver显示结果
            {

                pd = new ProgressDialog(ac);
                pd.setProgressStyle(TRIM_MEMORY_RUNNING_CRITICAL);
                pd.setMessage("正在搜索蓝牙。。");
                pd.setTitle("搜索设备");
                pd.show();
                lstDevices.clear();
                IDCardIdentificationManager.getInstance().scan(new BleScanCallback() {
                    @Override
                    public void onScanFinished(List<BleDevice> scanResultList) {
                        pd.dismiss();

                    }

                    @Override
                    public void onScanStarted(boolean success) {


                    }

                    @Override
                    public void onScanning(BleDevice bleDevice) {
                        {
                            // 扫描到一个符合扫描规则的BLE设备（主线程）

                            String str = bleDevice.getName() + "|" + bleDevice.getMac();

                            Log.e(TAG, "onReceive:================= " + str);

//				if ((lstDevices.indexOf(str) == -1)){//&&(device.getAddress().startsWith("20:16"))){
                            if ((lstDevices.indexOf(str) == -1)) {


                                lstDevices.add(str);
                                adtDevices.notifyDataSetChanged();

                                //lanyapeidui
                                pd.setMessage("蓝牙配对中...");
                                pd.dismiss();
                                String[] values = str.split("\\|");
                                String address = values[1];
                                Log.e("address", values[1]);


                            }
                        }
                    }
                });


            } else if (v == tbtnSwitch) {// 本机蓝牙启动/关闭
                if (tbtnSwitch.isChecked() == false) {
                    BleManager.getInstance().enableBluetooth();

                } else if (tbtnSwitch.isChecked() == true) {
                    BleManager.getInstance().disableBluetooth();
                }

            } else if (v == btnDis)// 本机可以被搜索
            {
                Intent discoverableIntent = new Intent(
                        BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                discoverableIntent.putExtra(
                        BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
                startActivity(discoverableIntent);
            } else if (v == btnExit) {

                ConnectSampleActivity.this.finish();
            }
        }

    }


}
